package com.javasee.rain.stock.util;

import com.javasee.rain.stock.model.StockBasic;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 股票列表缓存工具类
 * 
 * @author : xinyanfei
 * @date : 2025/10/11
 * Copyright (c) 2025, 京东商城 All Rights Reserved.
 */
public class StockCacheUtil {
    
    private static final Logger logger = LoggerFactory.getLogger(StockCacheUtil.class);
    
    // 缓存过期时间（小时）
    private static final int CACHE_EXPIRE_HOURS = 12;
    
    // 缓存存储
    private static final ConcurrentHashMap<String, CacheItem> cache = new ConcurrentHashMap<>();
    
    // 缓存项内部类
    private static class CacheItem {
        private final List<StockBasic> data;
        private final LocalDateTime createTime;
        
        public CacheItem(List<StockBasic> data) {
            this.data = data;
            this.createTime = LocalDateTime.now();
        }
        
        public List<StockBasic> getData() {
            return data;
        }
        
        public boolean isExpired() {
            return createTime.plus(CACHE_EXPIRE_HOURS, ChronoUnit.HOURS).isBefore(LocalDateTime.now());
        }
        
        public LocalDateTime getCreateTime() {
            return createTime;
        }
    }
    
    /**
     * 获取缓存的股票列表
     * 
     * @param cacheKey 缓存键
     * @return 缓存的股票列表，如果缓存不存在或已过期则返回null
     */
    public static List<StockBasic> get(String cacheKey) {
        CacheItem item = cache.get(cacheKey);
        if (item == null) {
            logger.debug("缓存未命中: {}", cacheKey);
            return null;
        }
        
        if (item.isExpired()) {
            logger.info("缓存已过期: {}, 创建时间: {}", cacheKey, item.getCreateTime());
            cache.remove(cacheKey);
            return null;
        }
        
        logger.debug("缓存命中: {}, 创建时间: {}", cacheKey, item.getCreateTime());
        return item.getData();
    }
    
    /**
     * 缓存股票列表
     * 
     * @param cacheKey 缓存键
     * @param stockList 股票列表
     */
    public static void put(String cacheKey, List<StockBasic> stockList) {
        if (stockList == null) {
            logger.warn("尝试缓存null数据: {}", cacheKey);
            return;
        }
        
        CacheItem item = new CacheItem(stockList);
        cache.put(cacheKey, item);
        logger.info("缓存已更新: {}, 数据量: {}, 过期时间: {}小时", 
                   cacheKey, stockList.size(), CACHE_EXPIRE_HOURS);
    }
    
    /**
     * 清除指定缓存
     * 
     * @param cacheKey 缓存键
     */
    public static void remove(String cacheKey) {
        CacheItem removed = cache.remove(cacheKey);
        if (removed != null) {
            logger.info("缓存已清除: {}", cacheKey);
        }
    }
    
    /**
     * 清除所有缓存
     */
    public static void clear() {
        int size = cache.size();
        cache.clear();
        logger.info("所有缓存已清除, 清除前缓存数量: {}", size);
    }
    
    /**
     * 清除过期缓存
     */
    public static void clearExpired() {
        int removedCount = 0;
        for (String key : cache.keySet()) {
            CacheItem item = cache.get(key);
            if (item != null && item.isExpired()) {
                cache.remove(key);
                removedCount++;
            }
        }
        
        if (removedCount > 0) {
            logger.info("清除过期缓存数量: {}", removedCount);
        }
    }
    
    /**
     * 获取缓存信息
     * 
     * @return 缓存信息字符串
     */
    public static String getCacheInfo() {
        StringBuilder info = new StringBuilder();
        info.append("缓存信息:\n");
        info.append("总缓存数量: ").append(cache.size()).append("\n");
        info.append("过期时间: ").append(CACHE_EXPIRE_HOURS).append("小时\n");
        
        for (String key : cache.keySet()) {
            CacheItem item = cache.get(key);
            if (item != null) {
                info.append("- ").append(key).append(": ")
                   .append(item.getData().size()).append("条数据, ")
                   .append("创建时间: ").append(item.getCreateTime()).append(", ");
                
                if (item.isExpired()) {
                    info.append("已过期");
                } else {
                    long hoursLeft = ChronoUnit.HOURS.between(LocalDateTime.now(), 
                                           item.getCreateTime().plus(CACHE_EXPIRE_HOURS, ChronoUnit.HOURS));
                    info.append("剩余").append(hoursLeft).append("小时过期");
                }
                info.append("\n");
            }
        }
        
        return info.toString();
    }
    
    /**
     * 检查缓存是否存在且未过期
     * 
     * @param cacheKey 缓存键
     * @return 是否存在有效缓存
     */
    public static boolean isValid(String cacheKey) {
        CacheItem item = cache.get(cacheKey);
        return item != null && !item.isExpired();
    }
}